var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var io = require('socket.io')();
var routes = require('./routes/index')(io);
var users = require('./routes/users');
var schedule = require("node-schedule");
var app = express();
var ipInfo = require('ipip')();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/monitor');
var Log = require('./model/Log');
var Record = require('./model/Record');



// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});



var rule = new schedule.RecurrenceRule();
var times = [];
for (var i = 1; i < 60; i++) {　　　
    times.push(i);
}　　
rule.second = times;　

module.exports = app;
app.io = io;
io.on('connection', function(socket) {
    socket.on('my other event', function(data) {
        console.log(data);
    });
});

var i = schedule.scheduleJob(rule, function() {　　
    var array = {};
    var records = [];
    var start = new Date().getTime();
    Log.find({
        isSend: 0
    }).sort({
        '_id': 1
    }).limit(500).exec(function(err, logs) {
        //console.log(logs.length);
        while (logs.length > 0) {
            var data = logs.shift();
            try {
                createArray(array, data);
            } catch (err) {
                console.log(err);
            }
        }
        io.sockets.emit('map', array);
    });
});
var j = schedule.scheduleJob(rule, function() {　　
    Record.find({}).sort({
        'count': -1
    }).exec(function(err, records) {
        var data = [];
        var total = 0;
        for (var i in records) {
            total += records[i].count;
            if (i < 10) {
                data.push(records[i]);
            }
        }
        io.sockets.emit('record', {
            data: data,
            total: total+200000000
        });
    });
});
var k = schedule.scheduleJob(rule, function() {　　
    Log.find({}).sort({
        '_id': -1
    }).limit(10).exec(function(err, logs) {
        io.sockets.emit('new', logs);
    });
});

var createArray = function(array, data) {
    if (array[data.remote_addr] == null) {
        array[data.remote_addr] = data;
        array[data.remote_addr].count = 1;
    } else {
        array[data.remote_addr].count += 1;
    }
    Log.update({
        _id: data._id
    }, {
        $set: {
            isSend: 1
        }
    }, function(err) {
        if (err != null) {
            console.log(err);
        }

    });
}
